package chatRoom.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

import chatRoom.ChatConnection;
import chatRoom.network.Connection;

public class Client implements Runnable 
{

	private Socket s;
	private Gui gu;
	private ChatConnection conn;
	private Thread connection;
	private Queue<Message> messages;
	
	public Client(String host, int port) throws UnknownHostException, IOException{
		s = new Socket(host, port);
		
		Connection connect = new ChatConnection(s); 
	    conn = (ChatConnection) connect;
	    
		connection = new Thread(connect);
		messages = new LinkedList<Message>();
	}
	
	public void run(){
		connection.start();
		
		while(true){
			receive();
		}
	}
	
	public Queue<Message> receiveMessages(){
		Queue<Message> temp = messages;
		messages = new LinkedList<Message>();
		return temp;
	}
	
	public void receive(){
		Queue<String> incoming = conn.getIn();
		
		for(String s : incoming){
			String cmd = s.substring(0, s.indexOf(" "));
			if(cmd.equals("PRIVMSG") || cmd.equals("WALLOPS")){
				String message = s.substring(s.indexOf(":")+1);
				String origin = s.substring(s.indexOf(" ")+1, s.indexOf(":"));
				String sender = origin.contains("!") ? s.substring(s.indexOf(" ")+1, s.indexOf("!")) : s.substring(s.indexOf(" ")+1, s.indexOf("%"));
				messages.add(new Message(sender, message));
			}
		}
	}
	
	public void send(String message){
		conn.send(message);
	}
}
